package com.btr.ivle;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.GetAnnouncementTask;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DataSourceAnnouncement;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.IsNetworkAvailable;

public class ListAnnouncementActivity extends SherlockListActivity implements 
	ActionBar.OnNavigationListener, AsyncTaskCompleteListener<String> {
	
	private Context myApp = this;
	private GetAnnouncementTask getAnnouncementTask;
	private List<Map<String, String>> list;
	private String CourseCode;
	public static String MSG_ID = "ListAnnouncementActivity.ID";
	private MenuItem item;
	//private boolean isRefreshed = false;
	private boolean isSelect = false;
	private boolean firstTime = true;
	
	private final String MAP_ID = "ID";
	private final String MAP_TITLE = "Title";
	private final String MAP_DESCRIPTION = "Description";
	private final String MAP_CREATEDDATE = "CreatedDate";
	private Integer position;

    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        
        Intent intent = getIntent();
        CourseCode = intent.getStringExtra(ListModuleItemActivity.EXTRA_MESSAGE_COURSECODE);
        try{
        	CourseCode = savedInstanceState.getString("CourseCode");
        	position = savedInstanceState.getInt("position");
    	}catch(Exception ex){
	    }
        setActionBar(CourseCode);
    }
    
    @Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putString("CourseCode", CourseCode);
	  savedInstanceState.putInt("position", position);
	}
    
    @Override
    public void onDestroy(){
    	if(this.getAnnouncementTask!=null)
    		this.getAnnouncementTask.cancel(true);
    	super.onDestroy();
    }
    
	public void onAsyncTaskComplete(String result) {
		getAnnouncementFromDB();
		if(item!=null)
			item.setActionView(null);
	}
    
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    	if(position!=itemPosition)
    		isSelect = true;
    	else
    		isSelect = false;
    	position = itemPosition;
    	
    	DatabaseModule db = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {db.colCode}; 
        String orderBy = db.colCode + " ASC"; 
        Cursor c = db.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToPosition(itemPosition);
        CourseCode = c.getString(0);
        
        //getAnnouncement
        getAnnouncementFromDB();
        
        if((!IVLEToken.isOffline()&&isSelect)||firstTime){
	        if(IsNetworkAvailable.check(myApp)){
	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	        	getAnnouncementTask = new GetAnnouncementTask(this);
		        getAnnouncementTask.execute(CourseCode);
	        }else{
	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	        	IVLEToken.setOffline(true);
	        }
	        firstTime = false;
        }
        
    	c.close();
        db.getReadableDatabase().close();
        db.close();
        return true;
    }
    
	private void getAnnouncementFromDB(){
		DataSourceAnnouncement datasource = new DataSourceAnnouncement(this);
		datasource.open();
		Cursor c = datasource.getAnnouncementsByCourseCode(CourseCode);
		
        Map<String, String> map;
        list = new ArrayList<Map<String, String>>();
        
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
        	Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(Long.parseLong(c.getString(3)));
            Date date = calendar.getTime();
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy EEE hh:mma");

            String htmltext = c.getString(2).replace("<br />", " ");
        	map = new HashMap<String, String>();
        	map.put(MAP_ID, c.getString(0));
        	map.put(MAP_TITLE, c.getString(1));
    		map.put(MAP_DESCRIPTION, Html.fromHtml(htmltext).toString());
    		map.put(MAP_CREATEDDATE, dateFormat.format(date));
    		
    		list.add(map);
	        c.moveToNext();
        }
        c.close();
        if(list.size()>0)
        	setListView(list);
	}
    
    private void setActionBar(String CourseCode){
    	final ActionBar ab = getSupportActionBar();
        Context context = ab.getThemedContext();
        ArrayAdapter<CharSequence> codeList = new ArrayAdapter<CharSequence>(context, R.layout.sherlock_spinner_item);
        
        DatabaseModule dbModule = new DatabaseModule(context,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {dbModule.colCode}; 
        String orderBy = dbModule.colCode + " ASC"; 
        Cursor c = dbModule.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToFirst();
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
    		codeList.add(c.getString(0));
    		if(c.getString(0).equals(CourseCode)){
    			position = i;
    		}
	        c.moveToNext();
        }
        c.close();
        dbModule.getReadableDatabase().close();
        dbModule.close();

        codeList.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ab.setListNavigationCallbacks(codeList, this);
        ab.setDisplayShowHomeEnabled(false);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setSelectedNavigationItem(position);
    }

    private void setListView(final List<Map<String, String>> list){  	
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.announcementlist,
                new String[]{MAP_TITLE,MAP_DESCRIPTION,MAP_CREATEDDATE},  
                new int[]{R.id.Title,R.id.Description,R.id.CreatedDate});
        setListAdapter(adapter);
        
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
        	  Intent intent = new Intent(ListAnnouncementActivity.this, ViewAnnouncementActivity.class);
	          intent.putExtra(MSG_ID, list.get(position).get(MAP_ID));
	          startActivity(intent);
          }
        });
	}
    
	public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.menu_refresh, menu);
        item = menu.findItem(R.id.refresh);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
	        case android.R.id.home:
	        	this.onBackPressed();
	        	break;
	        case R.id.refresh:
	        	this.item = item;
	            if(!IVLEToken.isOffline()){
	    	        if(IsNetworkAvailable.check(myApp)){
	    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	    	        	getAnnouncementTask = new GetAnnouncementTask(this);
	    		        getAnnouncementTask.execute(CourseCode);
	    	        }else{
	    	        	Toast.makeText(myApp, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	    	        	IVLEToken.setOffline(true);
	    	        }
	            }
	        	break;
    	}
          return true;
    }
    
    @Override
    public void onBackPressed(){
    	Intent intent = new Intent();
    	intent.putExtra("position", this.position.toString());
    	setResult(1, intent);
    	super.onBackPressed();
    }
}
